﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace SearchInFiles.Lib.Controls
{
    public class HighlightTextblock : TextBlock
    {
        public string SourceText { get => (string)GetValue(SourceTextProperty); set => SetValue(SourceTextProperty, value); }
        public static readonly DependencyProperty SourceTextProperty = DependencyProperty.Register("SourceText", typeof(string), typeof(HighlightTextblock), new PropertyMetadata(string.Empty, OnSourceTextChanged));
        private static void OnSourceTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d != null && d is HighlightTextblock htb)
                htb.UpdateHighText(e.NewValue?.ToString(), htb.HiText);
        }

        public string HiText { get => (string)GetValue(HiTextProperty); set => SetValue(HiTextProperty, value); }
        public static readonly DependencyProperty HiTextProperty = DependencyProperty.Register("HiText", typeof(string), typeof(HighlightTextblock), new PropertyMetadata(string.Empty, OnHiTextChanged));
        private static void OnHiTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d != null && d is HighlightTextblock htb)
                htb.UpdateHighText(htb.SourceText, e.NewValue?.ToString());
        }

        private void UpdateHighText(string? SourceText, string? hiText)
        {
            if (string.IsNullOrEmpty(SourceText))
            {
                Text = string.Empty;
                return;
            }
            if (!string.IsNullOrEmpty(hiText))
            {
                Text = string.Empty;
                
                string[] spli = SourceText.Split(hiText);
                for (int i = 0; i < spli.Length; i++)
                {
                    Inlines.Add(new Run(spli[i]));

                    if (i < spli.Length - 1)
                    {
                        int searchstart = Text.Length;
                        var iCaseTextIndex = SourceText.IndexOf(hiText, searchstart, StringComparison.OrdinalIgnoreCase);
                        if (iCaseTextIndex < 0)
                        {
                            continue;
                        }
                        string caseText = SourceText.Substring(iCaseTextIndex, hiText.Length);
                        Inlines.Add(new Run(caseText) { Background = Brushes.Yellow });
                    }
                }
            }
            else
            {
                Text = SourceText;
            }
        }
    }
}
